<?php
/**
 * ---------------------------------------------------
 * 用户常用操作
 * ---------------------------------------------------
 * 获取用户配置信息
 * 获取用户基本资料
 * 密码验证
 * 用户组
 * 		用户与组关联
 * 		
 * 获取用户全部信息
 * 用户登录
 * 
 * 获取SMW02平台信息
 * 获取O2O平台信息
 * 获取各平台余额信息
 * 注册新用户
 * 修改密码
 * 修改资料
 * 找回密码
 * select * FROM `user` as u LEFT JOIN user_ext as e ON u.id=e.userid where e.platform='SMW01' AND e.element='status' AND e.`value`='1' AND u.id=1
 */
class User{
	//用户基本信息
	//protected $userinfo = array();
	//用户配置信息
	protected $setupinfo = array();
	//用户组
	protected $usergroup = array();
	//用户组关联信息
	protected $usergroupinfo = array();
	//获取SMW02平台信息
	//protected $SMWinfo = array();
	//获取O2O平台信息
	//protected $O2Oinfo = array();
	public $platform = '';
	
	protected $userdao,$post;
	protected $userid=0;
	protected $debug=array();
	protected $isdebug = 0,$isecho = 0;
	
	//protected $debug_arr;
	
	protected $err_code = '';
	
	//用户关联表
	protected $user_ext,$user_money,$user_b2b,$role_user,$role,$user_o2o,$user_biz;
	/**
	 * 实例化用户类函数
	 * */
	function __construct($platform){
		$this->userdao = M('User');
		$this->user_ext = M('User_ext');
		$this->user_money = M('User_money');
		$this->user_b2b = M('User_b2b');
		$this->user_o2o = M('User_o2o');
		$this->user_biz = M('User_biz');
		$this->role_user = M('Role_user');
		$this->role = M('Role');
		
		$this->platform = $platform;
	}
	/**
	 * 访问商户站点返回商户用户ID
	 * */
	function get_domain_bizid(){
		$host = explode('.', $_SERVER['HTTP_HOST']);
		$site = array();
		if ( ($host[0]!='www') && (count($host)==2 || count($host)==3)) {
			if ( count($host) == 2 ) {
				$site = $this->get_data("site", array('link_url'=>'www'.$host['0'].'.'.$host['1']), 'user_id', false);
			}
			if ( count($host) == 3 ) {
				$site = $this->get_data("site", array('domain'=>$host['0']), 'user_id', false);
			}
		}
		if ( ($host[0]=='www') && (count($host)==3 || count($host)==4)) {
			if ( count($host) == 3 ) {
				$site = $this->get_data("site", array('link_url'=>$host['0'].$host['1'].'.'.$host['2']), 'user_id', false);
			}
			if ( count($host) == 4 ) {
				$site = $this->get_data("site", array('domain'=>$host['1']), 'user_id', false);
			}
		}
		return $site;
	}
	/**
	 * 添加用户(注册新用户)
	 * @param array $user 注册用户信息
	 * @param array $field_exist 要校验的不可重复的数据字段  array('username' => '用户名','email' => '信箱','mobile' => '手机')
	 * @param array $field_null 要校验的不可为空的数据字段  array('username' => '用户名','password' => '密码','email' => '信箱','mobile' => '手机')
	 * @param $role_id 注册用户用户组
	 * @param $recom 如果有推荐人就执行用户扩展表中插入推荐相关信息
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"id":序列号} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function user_add($user=array(),$field_exist=array(),$field_null=array(),$role_id=NULL,$recom=NULL){
		foreach ($field_null as $key => $value) {
			if(empty($user[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $user[$key])){
				return $this->_err($value."已存在");
			}
		}
		$this->post = $user;
		$this->post['password'] = md5($user['password']);
		$this->post['createtime'] = time();
		$this->post['status'] = 1;
		$resid = $this->insert();
		if(false !== $resid){
			if(!empty($this->platform)){
				if(!empty($role_id)){
					$role['role_id'] = $role_id;
					$role['user_id'] = $resid;
					$role['ctime'] = time();
					$this->insert_ext($this->role_user,$role);
				}
				if(!empty($recom)){
					$rcom['value'] = $recom;
					$rcom['userid'] = $resid;
					$rcom['element'] = "recom";
					$rcom['title'] = "推荐人";
					$rcom['platform'] = $this->platform;
					$this->insert_ext($this->user_ext,$rcom);
				}
				$ext['value'] = 1;
				$ext['userid'] = $resid;
				$ext['element'] = "status";
				$ext['title'] = "状态";
				$ext['platform'] = $this->platform;
				$this->insert_ext($this->user_ext,$ext);
			}
			$res=array('id'=>$resid);
			return $this->_suc($res,'注册成功');
		}else{
			return $this->_err("注册失败请重试");
		}
	}
	/**
	 * 给用户写入平台状态
	 * @param int $userid 用户ID
	 * @param string $platform 平台标识:SMW01,91YUNGOU
	 * @param int $isStatus 是否可用：1,0
	 * @return 成功返回  !=false
	 * */
	function set_platform_status($userid,$platform,$isStatus){
		return $this->insert_update('user_ext',array('userid'=>$userid,'platform'=>$platform,'element'=>'status'),array('value'=>$isStatus,'title'=>'状态'),true);
	}
	/**
	 * 给用户写入权限
	 * @param int $userid 用户ID
	 * @param int $roleid 用户组ID
	 * @param int $adminid 操作用户ID
	 * @return 成功返回  !=false
	 * */
	function set_role_user($userid,$roleid,$adminid){
		return $this->insert_update('role_user',array('role_id'=>$roleid,'user_id'=>$userid),array('ctime'=>time(),'mtime'=>time(),'adminid'=>$adminid));
	}
	/**
	 * 用户找回密码
	 * @param array $user 要校验的信息
	 * @param array $select_field 要修改密码的用户名  array('username' => $_REQUEST['username'])
	 * @return 成功返回 {"status":"1","msg":"密码重置成功","data":{"id":"13533","username":"liuhaonan","password":"edbb5c1b303c630b6db16cd2fea518a4","email":"liuhaonan_20032@163.com","mobile":"13528415952","login_count":"0","createtime":"1367836208","updatetime":"0","last_logintime":"","reg_ip":"","last_ip":"","status":"","avatar":"","newpassowrd":"353756"},"mStatus":"1"} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function back_password($user=array(),$select_field=array()){
		$userinfo = array();
		foreach ($select_field as $key => $value) {
			$userinfo = $this->select_field($key,$value);
		}
		$this->userid = $userinfo['id'];
		$this->post['id'] = $this->userid;
		if(empty($this->userid)){
			return $this->_err("没有要修改的数据或数据ID不可为空");
		}
		$ok_count = 0;
		foreach ($user as $key => $value) {
			if($userinfo[$key] == $value){
				$ok_count += 1;
			}
		}
		if($ok_count == 0){
			return $this->_err("您的验证信息有误");
		}
		$psd = rand(100000, 999999);
		$this->post['password'] = md5($psd);
		$status = $this->update();
		if(false !== $status){
			$this->debug = $userinfo;
			$this->debug['newpassowrd'] = $psd;
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'密码重置成功');
		}else{
			return $this->_err("密码重置失败请重试");
		}
	}
	/**
	 * 用户登录
	 * @param array $select_field 登录所用的用户名或其它 可以同使用=用户名/信箱/手机号/等等
	 * @param array $password_exist 要校验的用户密码  array('password' => $_REQUEST['password'])
	 * @param array $status 校验当前用户可用状态  array('status' => 1)
	 * @return 成功返回 {"status":"1","msg":"登录成功","data":{"id":"13533","username":"liuhaonan","password":"4eef1e1ea34879a2ae60c60815927ed9","email":"liuhaonan_20032@163.com","mobile":"13528415952","login_count":"0","createtime":"1367836208","updatetime":"0","last_logintime":"","reg_ip":"","last_ip":"","status":"","avatar":""},"mStatus":"1"} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function user_login($select_field=array(),$password_exist=array(),$status=array()){
		//$this->isecho = 1;
		$userinfo = array();
		$err_count = 0;
		$login_name_count = count($select_field);		
		foreach ($select_field as $key => $value) {
			if(empty($userinfo)){
				$userinfo = $this->select_field($key,$value);
				$err_count += 1;
			}
			foreach ($password_exist as $key => $value) {
				if($userinfo[$key] != md5($value)){
					if($err_count == $login_name_count){
						$this->err_code = __LINE__;return $this->_err("用户名或密码不正确");
					}else{
						$userinfo = "";
					}
				}else{
					$userinfo[$key] = "";
					foreach ($status as $key => $value) {
						if($userinfo[$key] != $value){
							$this->err_code = __LINE__;return $this->_err("帐户未开通或有异常,请联系客服人员.");
						}
					}
					$this->userid = $userinfo['id'];
					/*dump($this->select_ext($this->user_ext,array('userid' => 425,'platform' => 'SMW01'),"element,value"));
					dump($this->select_ext($this->user_money,array('userid' => 425,'platform' => 'SMW01'),"subject,value"));
					dump($this->select_ext($this->user_b2b,array('user_id' => 425),"realname,company,question,answer,sex,tel,mobile,fax,web_url,province,city,area,address,login_count,createtime,updatetime,last_logintime,reg_ip,last_ip,status,avatar,flink",false));*/
					$role = $this->select_ext($this->role_user,array('user_id' => $this->userid),"role_id");
					$role_name = array();
					foreach ($role as $key => $value) {
						$role_info=$this->select_ext($this->role,array('id' => $value['role_id'],'platform' => $this->platform),"id,name",false);
						if($role_info !== false){
							$role_name[$key] = $role_info;
						}
					}
					$user_ext=$this->select_ext($this->user_ext,array('userid' => $this->userid,'platform' => $this->platform),"platform,element,value");
					/*foreach ($status as $key => $value) {
						if($user_ext[0]['value'] != $value){
							$this->err_code = __LINE__;return $this->_err("平台未开通或有异常,请联系客服人员.");
						}
					}*/
					$res=array('mStatus'=>1,
								'user_ext'=>$user_ext,
								//'user_money'=>$this->select_ext($this->user_money,array('userid' => $this->userid,'platform' => $this->platform),"subject,value"),
								//'user_b2b'=>$this->select_ext($this->user_b2b,array('user_id' => $this->userid),"realname,company,question,answer,sex,tel,mobile,fax,web_url,province,city,area,address,login_count,createtime,updatetime,last_logintime,reg_ip,last_ip,status,avatar,flink",false),
								'role_user' => $role_name);
					$this->debug = $userinfo;//关联用户其它信息
					return $this->_suc($res,'登录成功');
				}
			}
		}
	}
	/**
	 * QQ登录
	 * @param int $openid qq登录产生的openid
	 * @return 成功返回 {"status":"1","msg":"登录成功","data":{"id":"13533","username":"liuhaonan","password":"4eef1e1ea34879a2ae60c60815927ed9","email":"liuhaonan_20032@163.com","mobile":"13528415952","login_count":"0","createtime":"1367836208","updatetime":"0","last_logintime":"","reg_ip":"","last_ip":"","status":"","avatar":""},"mStatus":"1"} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function user_qq_login($openid){
		$userinfo = array();
		//$userid = $this->get_data('user_ext',array('platform'=>$this->platform,'element'=>'qq','value'=>$openid),'userid',false);
		$userid = $this->get_data('user_ext',array('element'=>'qq','value'=>$openid),'userid,platform',false);
		if($userid !== false){
			$this->userdao = M('User');
			$userinfo = $this->select_field('id',$userid['userid']);
			$this->userid = $userinfo['id'];
			if($userinfo['status'] != 1){
				return $this->_err("帐户未开通或有异常,请联系客服人员.");
			}
			$role = $this->select_ext($this->role_user,array('user_id' => $this->userid),"role_id");
			$role_name = array();
			foreach ($role as $key => $value) {
				$role_info=$this->select_ext($this->role,array('id' => $value['role_id'],'platform' => $this->platform),"id,name",false);
				if($role_info !== false){
					$role_name[$key] = $role_info;
				}
			}
			$res=array('mStatus'=>1,
						'user_ext'=>$this->select_ext($this->user_ext,array('userid' => $this->userid,'platform' => $this->platform),"platform,element,value"),
						'role_user' => $role_name);
			$this->debug = $userinfo;//关联用户其它信息
			return $this->_suc($res,'登录成功');
		}
		return $userid;
	}
	
	/**
	 * 重置密码
	 * @param array $user 设置用户ID和新密码
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function password_reset($user=array()){
		$this->userid = $user['id'];
		if(empty($this->userid)){
			return $this->_err("没有要修改的数据或数据ID不可为空");
		}
	
		$this->post = $user;
		$status = $this->update();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	
	/**
	 * 修改密码
	 * @param array $user 设置用户ID和新密码
	 * @param array $field_null 要校验新密码不可以为空  array('password' => '新密码')
	 * @param array $old_password 设置校验旧密码  array('password' => $_REQUEST['old_password'])
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function password_edit($user=array(),$field_null=array(),$old_password=array()){
		$this->userid = $user['id'];
		if(empty($this->userid)){
			return $this->_err("没有要修改的数据或数据ID不可为空");
		}
		if(empty($old_password) || $old_password == 0){
			return $this->_err("请输入旧密码进行校验");
		}
		foreach ($field_null as $key => $value) {
			if(empty($user[$key])){
				return $this->_err($value."不能为空");
			}
		}
		$userinfo = $this->select($this->userid);
		foreach ($old_password as $key => $value) {
			if($userinfo[$key] != md5($value)){
				return $this->_err("旧密码不正确");
			}
			$user[$key] = md5($user[$key]);
		}
		$this->post = $user;
		$status = $this->update();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	/**
	 * 修改其它密码
	 * @param array $user 设置用户ID和新密码
	 * @param array $field_null 要校验新密码不可以为空  array('password' => '新密码')
	 * @param array $old_password 设置校验旧密码  array('password' => $_REQUEST['old_password'])
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function other_password_edit($tablename,$user=array(),$field_null=array(),$old_password=array(),$bool=true){
		$this->userdao = M($tablename);
		$this->userid = $user['id'];
		if(empty($this->userid)){
			return $this->_err("没有要修改的数据或数据ID不可为空");
		}
		if($bool == true && (empty($old_password) || $old_password == 0)){
			return $this->_err("请输入旧密码进行校验");
		}
		foreach ($field_null as $key => $value) {
			if(empty($user[$key])){
				return $this->_err($value."不能为空");
			}
		}
		$userinfo = $this->select($this->userid);
		foreach ($old_password as $key => $value) {
			if($bool == true && ($userinfo[$key] != md5($value))){
				return $this->_err("旧密码不正确");
			}
			$user[$key] = md5($user[$key]);
		}
		$this->post = $user;
		$status = $this->update();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	/**
	 * 删除信息
	 * @param array $tablename 设置要删除的信息表名称
	 * @param array $info 设置信息ID
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */
	function info_delete($tablename,$info=array()){
		$this->userdao = M($tablename);
		$this->userid = $info['id'];
		$status = $this->delete();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'删除成功');
		}else{
			return $this->_err("删除失败请重试");
		}
	}		
	/**
	 * 修改信息
	 * @param array $tablename 设置要修改的信息表名称
	 * @param array $user 设置用户ID和要修改用户信息
	 * @param array $field_exist 要校验的不可重复的数据字段 array('email' => '信箱','mobile' => '手机')
	 * @param array $field_null 要校验的不可为空的数据字段 array('email' => '信箱','mobile' => '手机')
	 * @Param array $$is_insert true 修改数据时ID为空时添加数据  false 不执行修改返回错误信息
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */	
	function user_edit($tablename,$user=array(),$field_exist=array(),$field_null=array(),$is_insert=false){
		$this->userdao = M($tablename);
		$this->userid = $user['id'];
		if(empty($this->userid)){
			if($is_insert==false){
				return $this->_err("没有要修改的数据或数据ID不可为空");
			}else{
				return $this->info_add($user,$field_exist,$field_null);
			}
		}
		foreach ($field_null as $key => $value) {
			if(empty($user[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $user[$key])){
				return $this->_err($value."已存在");
			}
		}
		
		$this->post = $user;
		$status = $this->update();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	/**
	 * 更新分销商平台信息
	 * @param array $tablename 设置要修改的信息表名称
	 * @param array $user 设置用户ID和要修改用户信息
	 * @param array $field_exist 要校验的不可重复的数据字段 array('email' => '信箱','mobile' => '手机')
	 * @param array $field_null 要校验的不可为空的数据字段 array('email' => '信箱','mobile' => '手机')
	 * @Param array $$is_insert true 修改数据时ID为空时添加数据  false 不执行修改返回错误信息
	 * @Param array $log=array(
	 * 					'type' => 触发类型,1申请 2付款 3审核 4状态
	 * 					'action_userid' => 操作用户,
	 * 					'remark' => 备注
	 * 					)
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}
	 * */	
	function set_agent_info($tablename,$user=array(),$field_exist=array(),$field_null=array(),$is_insert=false,$log=array()){
		$this->userdao = M($tablename);
		$this->userid = $user['id'];
		$logs = array();
		if(!empty($log)){
			$logs=$log;
			$logs['userid']=$user['user_id'];
		}
		if(empty($this->userid)){
			if($is_insert==false){
				return $this->_err("没有要修改的数据或数据ID不可为空");
			}else{
				return $this->info_add($user,$field_exist,$field_null,$logs);
			}
		}
		foreach ($field_null as $key => $value) {
			if(empty($user[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $user[$key])){
				return $this->_err($value."已存在");
			}
		}
		
		$this->post = $user;
		$status = $this->update();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'修改成功');
		}else{
			return $this->_err("修改失败请重试");
		}
	}
	/**
	 * 设置用户头像信息
	 * @param $tablename 用户数据表名
	 * @param $userid 用户ID
	 * @param $field_avatar 用户头像存储路径字段
	 * @param $upload_dir 用户头像文件存储目录
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data}  
	 * */
	function set_userlogo($tablename,$userid,$field_avatar,$upload_dir){
		$this->userdao = M($tablename);
		if(false !== $this->logo_upload($userid, $upload_dir)){
			$this->post['id'] = $userid;
			$this->post[$field_avatar] = $upload_dir.$userid.'.jpg';
			$status = $this->update();
			if(false !== $status){
				$res=array('mStatus'=>$status);
				return $this->_suc($res,'头像修改成功');
			}else{
				return $this->_err("头像修改失败请重试");
			}
		}else{
			return $this->_err("头像上传失败请重试");
		}
	}
	/**
	 * 添加信息
	 * @param array $user 设置添加信息
	 * @param array $field_exist 要校验的不可重复的数据字段 array('email' => '信箱','mobile' => '手机')
	 * @param array $field_null 要校验的不可为空的数据字段 array('email' => '信箱','mobile' => '手机')
	 * @Param array $log=array(
	 * 					'userid' => 帐户编号
	 * 					'type' => 触发类型,1申请 
	 * 					'action_userid' => 操作用户,
	 * 					'remark' => 备注
	 * 					)
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data} 
	 * */
	function info_add($user=array(),$field_exist=array(),$field_null=array(),$log=array()){
		foreach ($field_null as $key => $value) {
			if(empty($user[$key])){
				return $this->_err($value."不能为空");
			}
		}
		foreach ($field_exist as $key => $value) {
			if(false == $this->field_exist($key, $user[$key])){
				return $this->_err($value."已存在");
			}
		}
		$this->post = $user;
		$this->post['createtime'] = time();
		$resid = $this->insert();
		if(false !== $resid){
			$res=array('id'=>$resid);
			if(!empty($log)){
				$logs=$log;
				$logs['ctime'] = time();
				$this->insert_ext(M('UserAgentLog'),$logs);
			}
			return $this->_suc($res,'添加成功');
		}else{
			return $this->_err("添加失败请重试");
		}
	}	
	/**
	 * 删除用户
	 * @param $id 要删除的信息ID
	 * @return 返回删除成功信息 mStatus=1 否  0
	 * */
	function user_delete($id){
		$this->userid = $id;
		$status = $this->delete();
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'删除成功');
		}else{
			return $this->_err("删除失败请重试");
		}
	}
	/**
	 * 查询是否存在(并插入或更新)
	 * @param $table_ext   数据表名
	 * @param $field_value 查询条件和操作数据
	 * @param $field_ext   其它操作数据
	 * @param $isUpdate    是否要更新
	 * @param $isDelete    是否要删除
	 * @return 返回成功数据 否  false
	 * */
	function insert_update($table_ext,$field_value = array(),$field_ext = array(),$isUpdate = false,$isDelete = false){
		$this->userdao = M($table_ext);
		$info = $this->select_ext('',$field_value,'id',false);
		$new_arr = array();
		$new_arr = $field_value;
		if(!empty($field_ext)){
			$new_arr = array_merge($field_value,$field_ext);
		}
		if(false !== $info){
			if($isUpdate == true){
				return $this->update_ext('',$new_arr,$info['id']);
			}
			if($isDelete == true){
				return $this->delete_ext($info['id']);
			}
			return $info['id'];
		}else{
			if($isDelete == false){
				return $this->insert_ext('',$new_arr);
			}
		}
	}
	/**
	 * 返回用户基本信息
	 * */
	function get_info($table_ext,$field_value,$field,$isall){
		$this->isecho = 1;
		$info = $this->select_ext(M($table_ext),$field_value,$field,$isall);
		if(false !== $info){
			$res=array('info'=>$info);
			$this->_suc($res,'数据存在');
		}else{
			$this->_err("数据不存在");
		}
	}
	/**
	 * 返回查询表数据
	 * */
	function get_data($table_ext,$field_value,$field,$isall){
		return $this->select_ext(M($table_ext),$field_value,$field,$isall);
	}
	/**
	 * 注销用户信息
	 * */
	 function logout($arrSession) {
	 	if(!empty($arrSession)){
	 		foreach ($arrSession as $key => $value) {
				unset($_SESSION[$value]);
			}
	 	}else{
	 		unset($_SESSION);
	 	}
	}
	/**
	 * 返回地址数据
	 * @param $id 地址表ID
	 * @param $level 地址层级: 1省 2市 3区
	 * @param $provinceid 省级id
	 * @param $cityid 市级
	 * @param $areaid 区级
     * @return 地址json html option
	 * */
	function area($id,$level,$provinceid,$cityid,$areaid) {
		$module = M ( 'Area' );
		$id = intval ( $id );
		$level = intval ( $level );
		$provinceid = intval ( $provinceid );
		$cityid = intval ( $cityid );
		$areaid = intval ( $areaid );
		
		$province_str = '<option value="0">请选择省份...</option>';
		$city_str = '<option value="0">请选择城市...</option>';
		$area_str = '<option value="0">请选择区域...</option>';
		$str = '';
		
		$r = $module->where ( "parentid=" . $id )->select ();
        if(count($r)>0){
    		foreach ( $r as $key => $pro ) {
    			$selected = ($pro ['id'] == $provinceid) ? ' selected="selected" ' : '';
    			$str .= '<option value="' . $pro ['id'] . '"' . $selected . '>' . $pro ['name'] . '</option>';
    		}
		}else{
            $str.='<option value="-1" selected="selected">--无--</option>';
        }
		if ($level == 0) {
			$province_str .= $str;
		} elseif ($level == 1) {
			$city_str .= $str;
		} elseif ($level == 2) {
			$area_str .= $str;
		}
		$str = '';
		if ($provinceid) {
			
			$rr = $module->where ( "parentid=" . $provinceid )->select ();
			foreach ( $rr as $key => $pro ) {
				$selected = ($pro ['id'] == $cityid) ? ' selected="selected" ' : '';
				$str .= '<option value="' . $pro ['id'] . '"' . $selected . '>' . $pro ['name'] . '</option>';
			}
			$city_str .= $str;
		}
		$str = '';
		if ($cityid) {
			$rrr = $module->where ( "parentid=" . $cityid )->select ();
			if(count($rrr)>0){
				foreach ( $rrr as $key => $pro ) {
					$selected = ($pro ['id'] == $areaid) ? ' selected="selected" ' : '';
					$str .= '<option value="' . $pro ['id'] . '"' . $selected . '>' . $pro ['name'] . '</option>';
				}
			}else{
				$str.='<option value="-1" selected="selected">--无--</option>';
			}
			$area_str .= $str;
		}
		
		$res = array ();
		$res ['data'] = $rs ? 1 : 0;
		$res ['province'] = $province_str;
		$res ['city'] = $city_str;
		$res ['area'] = $area_str;
		echo json_encode ( $res );
		exit ();
	}
	/**
	 * 用户认证
	 * @param $userid 要认证的用户ID
	 * @param $platform 要认证的平台
	 * @param $element 要认证的mobile或email
	 * @param $title 认证注释标题
	 * @param $iscancel 设置取消认证 true 
     * @return 成功返回json相关数据
	 * */
	function user_verify($userid,$platform,$element,$title,$iscancel=false,$value=1){
		if($iscancel == false){
			$userinfo = $this->get_data("user_ext", array('userid' => $userid,'platform' => $platform,'element' => $element), "id,value", false);
			if(empty($userinfo) || $userinfo['value']!=$value){
				$extinfo = array();
				$res = array();
				if(!empty($userinfo['id'])){
					$extinfo ['id']   = $userinfo['id'];
					$extinfo ['value']   = $value;
					$res=$this->user_edit('user_ext',$extinfo,array(),array(),false);
				}else{
					$extinfo ['userid']   = $userid;
					$extinfo ['platform']   = $platform;
					$extinfo ['element']   = $element;
					$extinfo ['value']   = $value;
					$extinfo ['title']   = $title;
					$res=$this->user_edit('user_ext',$extinfo,array(),array(),true);
				}
				return $res;
			}
		}else{
			$userinfo = $this->get_data("user_ext", array('userid' => $userid,'platform' => $platform,'element' => $element), "id,value", false);
			if(empty($userinfo) || $userinfo['value']!=1){
				$extinfo = array();
				$res = array();
				if(!empty($userinfo['id'])){
					$extinfo ['id']   = $userinfo['id'];
					$extinfo ['value']   = 0;
					$res=$this->user_edit('user_ext',$extinfo,array(),array(),false);
				}
				return $res;
			}
		}
		
	}
	/**
	 * 获取用户相关扩展信息
	 * */
	function get_userext($userid){
		return $this->select_ext($this->user_ext,array('userid' => $userid),"platform,element,value");
	}
	/**
	 * 获取用户信息 帐户基本信息 用户扩展信息 用户权限信息 用户平台信息
	 * @param $username 用户帐户
	 * @param $platform_table 用户平台信息表名
     * @return 成功返回查询结果数组
	 * */
	function get_userinfo_all($username,$platform_table){
		$res = array();
		$res['user'] = $this->select_ext($this->userdao,array('username' => $username),'*',false);
		$res['user_ext'] = $this->select_ext($this->user_ext,array('userid' => $res['user']['id']));
		$res['role_user'] = $this->select_ext($this->role_user,array('user_id' => $res['user']['id']));
		$res['platform_info'] = $this->select_ext(M($platform_table),array('user_id' => $res['user']['id']),'*',false);
		return $res;
	}
	/**
	 * 获取用户扩展信息和用户权限信息
	 * @param int $userid 用户ID
	 * @param string $platform 平台标识:SMW01,91YUNGOU
     * @return array 扩展信息+权限信息
	 * */
	function get_user_ext_role($userid,$platform = false){
		$res = array();
		if($platform == false){
			$res['user_ext'] = $this->select_ext($this->user_ext,array('userid' => $userid),true);
		}else{
			$res['user_ext'] = $this->select_ext($this->user_ext,array('userid' => $userid,'platform' => $platform),true);
		}
		$res['role_user'] = $this->select_ext($this->role_user,array('user_id' => $userid));
		
		$role = $this->select_ext($this->role_user,array('user_id' => $userid),"role_id");
		$role_name = array();
		foreach ($role as $key => $value) {
			$role_name[$key] = $this->select_ext($this->role,array('id' => $value['role_id']),"id,name",false);
		}
		$res['role_user_name'] = $role_name;
		return $res;
	}
	/**
	 * 推荐客户列表
	 * @param $userid 用户ID
	 * @param $platform 平台标示
	 * @param $element 扩展类型
     * @return 成功返回查询结果数组
	 * */
	function recom_user($userid,$platform = '91YUNGOU',$element = 'recom' ,$limit = '0,20', $order = 'id DESC'){
		$model = D('Recom');
		$where = array('value' => $userid,'platform' => $platform,'element' => $element);
		if (strtolower ( $limit ) == 'all') {
			return $model->where($where)->count ();
		}
		$rel = $model->where($where)->order ( $order )->limit ( $limit )->select();
		return $rel;
	}
	/**
	 * 云购店列表
	 * @param $userid 用户ID
	 * @param $platform 平台标示
	 * @param $element 扩展类型
     * @return 成功返回查询结果数组
	 * */
	function cloudshop_user($userid,$platform = 'SMW01',$element = 'cloudshop' ,$limit = '0,200', $order = 'id DESC'){
		$model = D('Cloudshop');
		$where = array('value' => $userid,'platform' => $platform,'element' => $element);
		if (strtolower ( $limit ) == 'all') {
			return $model->where($where)->count ();
		}
		$rel = $model->where($where)->order ( $order )->limit ( $limit )->select();
		return $rel;
	}
	

	/**
	 * 客户注册信息统计
	 * */
	function user_count($user_id){
		$recom = D('Recom');
		$cloudshop = D('Cloudshop');
		$total_recom = $this->recom_user($user_id, '91YUNGOU', 'recom','all');
		$total_cloudshop = $this->cloudshop_user($user_id, 'SMW01', 'cloudshop','all');
		$count['total'] = intval($total_recom)+intval($total_cloudshop);
	
		// 		$where = array('value' => $userid,'platform' => '91YUNGOU','element' => 'recom');
		// 		$starttime=mktime(00,00,00,date('n'),date('d'),date('Y'));
		// 		$endtime=mktime(23,59,59,date('n'),date('d'),date('Y'));
		// 		$where['createtime'] = array(array('egt',$starttime),array('elt',$endtime));
		// 		$rel = $recom->where($where)->select();echo $recom->getLastSql();
		// 		$rel2 = $cloudshop->where($where)->select();
		return $count;
	}
	/**
	 * 获取当前会员上级
	 * @param $userid 用户ID
	 * @param $platform 平台
	 * @param $element 上级类型
     * @return 成功返回查询结果数组
	 * */
	function get_superiors($userid,$platform = 'SMW01',$element = 'cloudshop'){
		$arr_role_id = $this->select_ext($this->role_user,array('user_id' => $userid),"role_id");
		
		foreach ($arr_role_id as $key => $value) {
			if($value['role_id'] == 15){
				return $userid;
			}
		}
		
		$res = $this->select_ext($this->user_ext,array('userid' => $userid,'platform' => $platform,'element' => $element),"value",false);
		if(false!==$res){
			return $res['value'];
		}
		return $userid;
	}
	/**
	 * 设置组合查询用户关联表
	 * */
	function user_ext(){
		
	}
	/**
	 * 查询返回当前用户基本信息
	 * */
	function user_find(){
		
	}
	/**
	 * 查询返回当前用户帐户余额
	 * */
	function user_money(){
		
	}
	/**
	 * 查询返回所有用户信息
	 * */
	function user_select(){
		
	}
	public function user_check($fn, $val){
		return $this->_check($fn, $val);
	}
	/**
	 * 校验用户名是否合法
	 * */
	private function _check($fn,$val){
		$model = $this->userdao;
        $rel = $model->where($fn."='".$val."'")->find();
        if($rel !== false || !empty($rel)){
            return $rel;
        }else{
            return false;
        }
	}
	/**
	 * 校验密码加密类型
	 * */
	private function password_check(){
		
	}
	/**
     * 查询某个字段是否存在
	 * @param $fn 表字段名
	 * @param $val 值
     * @return 如果存在返回false，不存在返回true
     */
    private function field_exist($fn,$val){
        $model = $this->userdao;
        $rel = $model->where($fn."='".$val."'")->find();
		//$this->debug = $model->getlastsql();
        if($rel === false || empty($rel) || $rel['id'] == $this->userid){
            return true;
        }else{
            return false;
        }
    }
    /**
	 *请求接口类型异常
	 *@date 2012-05-06
	 *@time 上午08:10:19
	 */
	private function _err($str="暂无相关信息") {
		if($this->isecho == 1){
			//请求接口类型异常
			$res = array("status"=>0,"msg"=>$str,'data'=>$this->debug,'err_code'=>$this->err_code);
			if($this->isdebug==1){
				echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
			}
			echo $this->myjson($res);
			if($this->isdebug==1){
				echo '</textarea>';
			}
			die();
		}else{
			$res = array("status"=>0,"msg"=>$str,'data'=>$this->debug,'err_code'=>$this->err_code);
			return $this->myjson($res);
		}
		
	}//end _err
	
	/**
	 *请求成功返回
	 *@date 2012-05-06
	 *@time 上午08:10:19
	 */
	private function _suc($arr=array(),$str="操作成功") {
		if($this->isecho == 1){
			//请求接口类型异常
			$res = array("status"=>1,"msg"=>$str,'data'=>$this->debug);
			if(!empty($arr)){
				$res=array_merge($res,$arr);
			}
			if($this->isdebug==1){
				echo '<br>输出的数据:<br><textarea rows="15" cols="120">';
			}
			echo $this->myjson($res);
			if($this->isdebug==1){
				echo '</textarea>';
			}
			die();
		}else{
			$res = array("status"=>1,"msg"=>$str,'data'=>$this->debug);
			if(!empty($arr)){
				$res=array_merge($res,$arr);
			}
			return $this->myjson($res);
		}
		
	}//end _suc
	/**
	 * 对url或其它字符转义
	 * */
	private function myjson($code) {
		$code = json_encode ( $this->urlencodeAry ( $code ) );
		return urldecode ( $code );
		//return $code;
	}
	private function urlencodeAry($data) {
		if (is_array ( $data )) {
			foreach ( $data as $key => $val ) {
				$data [$key] = $this->urlencodeAry ( $val );
			}
			return $data;
		} else {
			return urlencode ( $data );
		}
	}
	
	/**
	 * 操作插入数据表
	 * */
	private function insert(){
		$model = $this->userdao;
		$_POST = $this->post;
		if (false === $model->create ()) {
			return false;
		}
		$result = $model->add ();
		//dump($model->getLastSql());exit;
		//$this->debug = $model->getLastSql();
		//$this->debug_arr += 1;
		//F('new_sql'.$this->debug_arr,$model->getLastSql());
		if ($result !== false) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作更新数据表
	 * */
	private function update(){
		$model = $this->userdao;
		if (false === $model->create ($this->post)) {
			return false;
		}
		$result = $model->save ();
		//$this->debug = $model->getlastsql();
		if (false !== $result) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 设置默认选中信息相同条件取消选中
	 * @param array $tablename 批量更新的数据表
	 * @param array $info 默认选中的信息
	 * @param array $batch_term 批量更新条件
	 * @param array $batch_info 批量更新的字段数据
	 * @return 成功返回 {"status":"1","msg":"信息","data":data,"mStatus":是否执行修改} 失败返回 {"status":"0","msg":"信息","data":data} 
	 * */
	function set_batch($tablename,$info=array(),$batch_term=array(),$batch_info=array()){
		$status = $this->batch_update($tablename,$info,$batch_term,$batch_info);
		if(false !== $status){
			$res=array('mStatus'=>$status);
			return $this->_suc($res,'更新成功');
		}else{
			return $this->_err("更新失败请重试");
		}
	}
	/**
	 * 批量更新
	 * @param array $batch_term 批量更新条件
	 * @param array $batch_info 批量更新的字段数据
	 * @return 成功返回true 失败返回 false
	 * */
	function batch_update($tablename,$info=array(),$batch_term=array(),$batch_info=array()){
		$this->userdao = M($tablename);
		$upid = $info['id'];
		$this->post = $info;
		$result = $this->update();
		if (false !== $result) {
			$info_list = $this->get_data($tablename,$batch_term,'id',true);
			$ret = false;
			foreach ($info_list as $key => $value) {
				if($info_list[$key]["id"]!=$upid){
					$this->post = $batch_info;
					$this->post['id'] = $info_list[$key]["id"];
					$ret=$this->update();
				}else{
					$ret = $result;
				}
			}
			return $ret;
		}
	}
	/**
	 * 操作删除数据表
	 * */
	private function delete(){
		$model = $this->userdao;
		$result = $model->delete ($this->userid);
		if (false !== $result) {
			return $result;
		} else {
			return false;
		}
	}
	/**
	 * 操作查询数据表
	 * @param $id 查询用户ID
	 * @return 如果存在返回用户信息，不存在返回false，参数$id空返回所有用户信息
	 * */
	private function select($id){
		$model = $this->userdao;
		if(!empty($id)){
			$result = $model->find ($id);
			return $result;
		}else{
			$result = $model->select ();
			return $result;
		}
	}
	/**
	 * 操作添加用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义插入字段和数值
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function insert_ext($table_ext,$field_value = array()){
		if(!empty($table_ext)){
			$this->userdao = $table_ext;
		}
		$this->post = $field_value;
		$rel = $this->insert();
		return $rel;
	}
	/**
	 * 操作更新用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义插入字段和数值
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function update_ext($table_ext,$field_value = array(),$id){
		if(!empty($table_ext)){
			$this->userdao = $table_ext;
		}
		if(!empty($id)){
			$field_value['id'] = $id;
			$this->post = $field_value;
		}
		$rel = $this->update();
		return $rel;
	}
	/**
	 * 操作删除用户关联扩展或附属数据表
     * @return 如果成功返回相关信息，失败在返回false
	 * */
	private function delete_ext($id){
		if(!empty($id)){
			$this->userid = $id;
		}
		$rel = $this->delete();
	}
	/**
	 * 操作查询用户关联扩展或附属数据表
	 * @param $table_ext 自定义表名
	 * @param $field_value 自定义查询条件
	 * @param $field 自定义数据字段
	 * @param $isall 是否全部查询  是：true 否：false
     * @return 如果存在返回查询信息，不存在返回false
	 * */
	private function select_ext($table_ext,$field_value = array(),$field = "*",$isall = true){
		if(!empty($table_ext)){
			$this->userdao = $table_ext;
		}
		$rel = $this->select_all($field_value,$field,$isall);
		return $rel;
	}
	/**
     * 自定义查询条件查询数据
	 * @param array $field_value 自定义查询条件
	 * @param $field 自定义数据字段
	 * @param $isall 是否全部查询  是：true 否：false
     * @return 如果存在返回所有信息，不存在返回false
     */   
    private function select_all($field_value = array(),$field = "*",$isall = true){
        $model = $this->userdao;
		$where = "";
		foreach ($field_value as $key => $value) {
			if(empty($where)){
				$where = $key."='".$value."'";
			}else{
				$where .= " AND ".$key."='".$value."'";
			}
		}
		$rel = array();
		if($isall == true){
			$rel = $model->field($field)->where($where)->select();
			//$this->debug = $model->getlastsql();
		}else{
			$rel = $model->field($field)->where($where)->find();
			//$this->debug = $model->getlastsql();
		}
        if(!empty($rel)){//$rel !== false ||
            return $rel;
        }else{
            return false;
        }
    }
	/**
     * 查询用户是否存在
	 * @param $fn 表字段名
	 * @param $val 值
     * @return 如果存在返回一条用户信息，不存在返回false
     */
    private function select_field($fn,$val){
        $model = $this->userdao;
        $rel = $model->where($fn."='".$val."'")->find();
        if($rel !== false || !empty($rel)){
            return $rel;
        }else{
            return false;
        }
    }
	/**
	 * 上传用户在线编辑剪切的头像
	 * @param $filename 头像文件名称
	 * @param $upload_dir 头像文件
     * @return bool
	 * */
	private function logo_upload($filename,$upload_dir){
		//$filename="teststream.jpg";//要生成的图片名字
		if(empty($filename) || empty($upload_dir)){
     		return false;
     	}
		$filename=$filename.".jpg";//要生成的图片名字  
	    $xmlstr = $GLOBALS[HTTP_RAW_POST_DATA];
	    if(empty($xmlstr)) {
	        $xmlstr = file_get_contents('php://input');
	    }
	     
	    $jpg = $xmlstr;//得到post过来的二进制原始数据
	    //$file = fopen("Uploads/logo/".$filename,"w");//打开文件准备写入
	    $file = fopen($upload_dir.$filename,"w");//打开文件准备写入
	    fwrite($file,$jpg);//写入
	    fclose($file);//关闭
	    return true;
	}
}
